package com.sxf.core.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * 
 * @description: 数字判定校验实现
 * @author: zhangyb@ccccit.com.cn 
 * @date: 2021年1月6日 下午2:50:55
 */
public class AllowedNumberValidator implements ConstraintValidator<AllowedNumber, Number> {

	private long[] allowedValues;
	
	private boolean checkNull;

	@Override
	public void initialize(AllowedNumber constraintAnnotation) {
		this.allowedValues = constraintAnnotation.values();
		this.checkNull = constraintAnnotation.checkNull();
	}

	@Override
	public boolean isValid(Number value, ConstraintValidatorContext context) {
		if(!checkNull && value == null) {
			return true;
		}
		
		if (value == null) {
			return false;
		}

		if (allowedValues != null && allowedValues.length > 0) {
			if (value instanceof BigDecimal) {
				return isBigDecimalInAllowedValues((BigDecimal) value);
			}

			if (value instanceof BigInteger) {
				return isBigIntegerInAllowedValues((BigInteger) value);
			}

			return isLongInAllowedValues(value.longValue());
		}
		return true;
	}

	private boolean isBigDecimalInAllowedValues(BigDecimal value) {
		for (long allowedValue : allowedValues) {
			if (value.compareTo(BigDecimal.valueOf(allowedValue)) == 0) {
				return true;
			}
		}
		return false;
	}

	private boolean isBigIntegerInAllowedValues(BigInteger value) {
		for (long allowedValue : allowedValues) {
			if (value.compareTo(BigInteger.valueOf(allowedValue)) == 0) {
				return true;
			}
		}
		return false;
	}

	private boolean isLongInAllowedValues(long value) {
		for (long allowedValue : allowedValues) {
			if (value == allowedValue) {
				return true;
			}
		}
		return false;
	}

}
